package im

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"log"
	"net/http"
	"wave-service/server/app/chat"
	"wave-service/server/app/common/jwtx"
	"wave-service/server/app/internal/svc"
)

type Server struct {
	Ctx    context.Context
	SvcCtx *svc.ServiceContext
}

func (i Server) Start() {
	i.Run()
}
func (i Server) Stop() {
	fmt.Println("im service was stop...")
}

func (i Server) Run() {
	mux := http.NewServeMux()
	mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		i.Ctx = context.Background()
		token := r.FormValue("token")
		if token == "" {
			log.Println("token为空")
			logx.Error("token为空")
			return
		}
		uid := jwtx.GetUserID(i.SvcCtx.Config.Auth.AccessSecret, token)
		if uid == 0 {
			log.Println("token解析错误")
			logx.Error("token解析错误")
			return
		}
		info, err := i.SvcCtx.VisitorsModel.FindOne(i.Ctx, uid)
		if err != nil {
			log.Println("ws 连接错误，未找到对应用户 %d", uid)
			logx.Errorf("ws 连接错误，未找到对应用户 %d", uid)
			return
		}
		log.Println("info.Uuid ws 连接成功", info.Uuid)
		chat.NewServer(w, r, info.Uuid, &Data{ctx: i.Ctx, svcCtx: i.SvcCtx})
	})
	fmt.Printf("Starting Ws Server at 0.0.0.0:%v...\n", i.SvcCtx.Config.WsPost)
	err := http.ListenAndServe(fmt.Sprintf(":%v", i.SvcCtx.Config.WsPost), mux)
	if err != nil {
		fmt.Println("ws err：", err)
		return
	}
}

type Data struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 发送消息回调
func (d *Data) SendMessage(msg chat.Message) {
	fmt.Println("发送消息回调: ", msg.String())
	SaveMessage(msg, d.ctx, d.svcCtx)
}

// 未读消息回调
func (d *Data) DelaySendMessage(msg chat.Message) {
	fmt.Println("Delay消息: ", msg.String())
	SaveDelayMessage(msg, d.ctx, d.svcCtx)
}

// 登录成功后回调
func (d *Data) LoginServer(uuid string) {
	log.Println("登录成功后回调: ")
	LoginSuccess(uuid, d.ctx, d.svcCtx)
}

// 退出登录回调
func (d *Data) LogoutServer(uuid string) {
	fmt.Println("退出成功后回调: ", uuid)
	LogoutSuccess(uuid, d.ctx, d.svcCtx)
}
func (d *Data) ErrorLogServer(err error) {
	// 错误消息回调
	fmt.Println("err: ", err)
	logx.Error(err)
}
